var formidable = require('formidable');
var util = require('util');
var exec = require('child_process').exec;

function load(request, response, parameters) {
  if (request.method.toLowerCase() == 'post') {
    upload(request, response);
  } else {
    require('../view_handler').render_view(request, response, 'view/upload.html');
  }
}

function upload(request, response) {
  var form = new formidable.IncomingForm();
  
  form.parse(request, function(err, fields, files) {
    exec('mv -f ' + files.uploaded_file.path + ' ~/anexos/' + files.uploaded_file.name);
    
    status = '<b>Arquivo:</b>: ' + files.uploaded_file.name +
             '<br><b>Tipo:</b> ' + files.uploaded_file.type +
             '<br><b>Tamanho:</b> ' + (files.uploaded_file.size / 1024) + ' kb';
    render_uploaded_succesfully(response, status);
  });  
}

function render_uploaded_succesfully(response, status) {
  response.writeHead(200, {'content-type': 'text/html'});
  response.write("<html> <head> <title>Conserpro: Upload</title> </head>" +
    "<body> <h2>Arquivo enviado com sucesso.</h2> <p/>" +
    status +
    "<p/><input type='button' value='Voltar' onClick='location.href=\"upload\"'/> </body></html>");
  response.end();
}

exports.load = load;
